package com.supermap.wzhy.common.entity;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Created by duanxiaofei on 2016/4/19.
 */
public class VoDiff<T> {

    /**
     * 来源对象和目标对象不同字段更新
     * @param src
     * @param dest
     * @throws IllegalAccessException
     */
    public void diff(T src, T dest) throws IllegalAccessException {
        Field[] fields = dest.getClass().getDeclaredFields();
        for (Field field : fields) {
            if(Modifier.isStatic(field.getModifiers())){
                continue;
            }
            field.setAccessible(true);
            Object val = field.get(dest);
            if(val==null){
                continue;
            }
            String type = field.getType().toString();
            if (type.endsWith("String")) {
                field.set(src, val.toString());
            } else if (type.endsWith("int") || type.endsWith("Integer")) {
                field.set(src, Integer.valueOf(val.toString()));
            } else if (type.endsWith("double") || type.endsWith("Double")){
                field.set(src, Double.valueOf(val.toString()));
            }
        }

    }

    /**
     * 判断来源对象和目标对象在一列上是否有变化
     * @param src 来源对象
     * @param dest 目标对象
     * @param columnName 指定列
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public boolean isChange(T src, T dest,String columnName) throws NoSuchFieldException, IllegalAccessException {
        Field field = dest.getClass().getDeclaredField(columnName);
        field.setAccessible(true);
        Object srcVal=field.get(src);
        Object destVal=field.get(dest);
        if((srcVal.hashCode()==dest.hashCode()) || (srcVal==null && destVal==null)){
            return false;
        }
        return true;
    }
}
